package com.ncst.backend.controller;

import com.ncst.backend.common.Result;
import com.ncst.backend.domain.InspectionRequest;
import com.ncst.backend.domain.MedicalTechnology;
import com.ncst.backend.domain.Register;
import com.ncst.backend.service.InspectionRequestService;
import com.ncst.backend.service.MedicalTechnologyService;
import com.ncst.backend.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 窗口退费控制器
 */
@RestController
@RequestMapping("/fee/refund")
public class FeeRefundController {
    
    @Autowired
    private InspectionRequestService inspectionRequestService;
    
    @Autowired
    private MedicalTechnologyService medicalTechnologyService;
    
    @Autowired
    private RegisterService registerService;
    
    /**
     * 分页查询退费列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getRefundList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String caseNumber,
            @RequestParam(required = false) String realName,
            @RequestParam(required = false) String inspectionState,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String techName) {
        
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> dataList = new ArrayList<>();
            
            // 处理精准搜索：根据病历号或姓名查询register
            List<Register> registerList = new ArrayList<>();
            if (caseNumber != null || realName != null) {
                Register register = new Register();
                register.setCaseNumber(caseNumber);
                register.setRealName(realName);
                registerList = registerService.getByCondition(register);
            }
            
            // 根据registerId查询inspection_request
            List<InspectionRequest> inspectionRequests = new ArrayList<>();
            if (!registerList.isEmpty()) {
                List<Integer> registerIds = registerList.stream().map(Register::getId).collect(Collectors.toList());
                for (Integer registerId : registerIds) {
                    List<InspectionRequest> requests = inspectionRequestService.getByRegisterId(registerId);
                    inspectionRequests.addAll(requests);
                }
            } else {
                // 没有精准搜索条件，按其他条件查询
                InspectionRequest inspectionRequest = new InspectionRequest();
                inspectionRequest.setInspectionState(inspectionState);
                inspectionRequests = inspectionRequestService.getByPage(pageNum, pageSize, inspectionRequest, startDate, endDate);
            }
            
            // 处理项目名称筛选
            if (techName != null && !techName.isEmpty()) {
                List<MedicalTechnology> techList = medicalTechnologyService.getByName(techName);
                if (!techList.isEmpty()) {
                    List<Integer> techIds = techList.stream().map(MedicalTechnology::getId).collect(Collectors.toList());
                    inspectionRequests = inspectionRequests.stream()
                            .filter(request -> techIds.contains(request.getMedicalTechnologyId()))
                            .collect(Collectors.toList());
                } else {
                    // 如果没有匹配的项目，返回空列表
                    inspectionRequests = new ArrayList<>();
                }
            }
            
            // 构建返回数据
            for (InspectionRequest request : inspectionRequests) {
                Map<String, Object> dataMap = new HashMap<>();
                
                // 获取患者信息
                Register register = registerService.getById(request.getRegisterId());
                if (register != null) {
                    dataMap.put("caseNumber", register.getCaseNumber());
                    dataMap.put("realName", register.getRealName());
                }
                
                // 获取项目信息
                MedicalTechnology tech = medicalTechnologyService.getById(request.getMedicalTechnologyId());
                if (tech != null) {
                    dataMap.put("techName", tech.getTechName());
                    dataMap.put("techPrice", tech.getTechPrice());
                } else {
                    dataMap.put("techName", "未知项目");
                    dataMap.put("techPrice", new BigDecimal(0));
                }
                
                // 设置其他信息
                dataMap.put("quantity", 1); // 假设数量默认为1
                dataMap.put("creationTime", request.getCreationTime());
                dataMap.put("id", request.getId());
                
                dataList.add(dataMap);
            }
            
            // 分页处理
            int total = dataList.size();
            int start = (pageNum - 1) * pageSize;
            int end = Math.min(start + pageSize, total);
            List<Map<String, Object>> pageList = start < total ? dataList.subList(start, end) : new ArrayList<>();
            
            result.put("list", pageList);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("pages", (total + pageSize - 1) / pageSize);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取退费列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 单条退费
     */
    @PostMapping("/single")
    public Result<Map<String, Object>> refundSingle(@RequestParam Integer id) {
        try {
            boolean success = inspectionRequestService.refundById(id);
            Map<String, Object> data = new HashMap<>();
            data.put("success", success);
            data.put("message", success ? "退费成功" : "退费失败");
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("单条退费失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量退费
     */
    @PostMapping("/batch")
    public Result<Map<String, Object>> refundBatch(@RequestBody List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.badRequest("请选择要退费的项目");
            }
            
            boolean success = inspectionRequestService.batchRefund(ids);
            Map<String, Object> data = new HashMap<>();
            data.put("success", success);
            data.put("message", success ? "批量退费成功" : "批量退费失败");
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量退费失败: " + e.getMessage());
        }
    }
}